package com.zhanghang.vending_machine.controller;


import com.zhanghang.vending_machine.common.result.Result;
import com.zhanghang.vending_machine.common.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @ApiOperation("文件上传接口")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);

        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //通过uuid生成新的文件名
            String newFile = UUID.randomUUID() + extension;

            //文件访问网址
            String filePath = aliOssUtil.upload(file.getBytes(), newFile);

            return Result.success(filePath);
        } catch (IOException e) {
            log.info("文件上传失败：{}",e);
        }
        return Result.error("文件上传失败");
    }//https://zhanghang-vending-machine.oss-cn-beijing.aliyuncs.com/47346759-011c-441b-ae91-bedef2d0f4b2.png
}
